package com.weimob.mcloud.wechatwork.customer.facade.impl.customer;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.core.adapter.enums.channel.WechatWorkAppType;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.request.SelfExternalContactGetDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.SelfExternalContactGetBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.passport.response.PassPortAccountMappingRes;
import com.weimob.mcloud.wechatwork.core.adapter.service.ChannelAdapterService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.enums.privateSphere.PrivateSphereEncryptCorpEnum;
import com.weimob.mcloud.wechatwork.customer.convertor.customer.PassportMappingCovert;
import com.weimob.mcloud.wechatwork.customer.third.NewRemoteOutServiceProxy;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.soa.common.response.SoaResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 接口列表
 * 1、查询passport，获取wid和externalUserId映射关系,支持批量，每批20
 * List<PassPortAccountMappingRes> queryAccountMapping(String corpId, Long bosId, List<Long> widList)
 *
 * 2、查询passport，拿wid换externalUserId,对接口1的返回值做处理
 * Set<String> queryExternalUserIdByWids(String corpId, Long bosId, List<Long> widList)
 *
 * 3、查询渠道获取腾讯客户数据，根据externalUserId查询客户详情
 * SelfExternalContactGetBO queryTXCustomerInfo(PrivateSphere privateSphere, String externalUserId)
 *
 * @author lvjunlong
 * @date 2022-11-02
 */
@Slf4j
@Service
public class CustomerFacadeV2 {

    @Value("${wid.partition.count:20}")
    private Integer widPartitionCount;

    @Autowired
    private NewRemoteOutServiceProxy remoteOutServiceProxy;

    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Value("${customer.query.byId.partition.count:20}")
    private Integer externalUserIdPartitionCount;

    @Autowired
    private ChannelAdapterService channelAdapterService;

    /**
     * 查询passport，根据wid换externalUserId
     * @param corpId
     * @param bosId
     * @param widList
     * @return
     */
    public List<PassPortAccountMappingRes> queryAccountMapping(String corpId, Long bosId, List<Long> widList) {
        if (CollectionUtils.isEmpty(widList)) {
            return new ArrayList<>();
        }

        List<List<Long>> widPartition = Lists.partition(widList, widPartitionCount);

        List<PassPortAccountMappingRes> passportAccountMappingRes = new ArrayList<>();
        for (List<Long> partWidList : widPartition) {
            //根据wid查询externalUserId
            List<PassPortAccountMappingRes> passportAccountMapping = remoteOutServiceProxy.getPassportAccountMappingRes(bosId, corpId, partWidList, null);
            if (CollectionUtils.isEmpty(passportAccountMapping)) {
                continue;
            }

            passportAccountMappingRes.addAll(passportAccountMapping);
        }


        return passportAccountMappingRes;
    }


    /**
     * 根据wid换externalUserId
     * @param privateSphere privateSphere
     * @param widList
     * @return
     */
    public Set<String> queryExternalUserIdByWids(PrivateSphere privateSphere, List<Long> widList) {
        String corpId = privateSphere.getCorpId();
        Long bosId = privateSphere.getBosId();
        List<PassPortAccountMappingRes> passPortAccountMappingRes = queryAccountMapping(corpId, bosId, widList);
        if (CollectionUtils.isEmpty(passPortAccountMappingRes)) {
            return new HashSet<>();
        }

        return PassportMappingCovert.toExternalUserIds(passPortAccountMappingRes);
    }

    /**
     * 根据externalUserId查询客户基本信息
     *
     * @param privateSphere   privateSphere
     * @param externalUserIds externalUserIds
     * @return
     */
    public List<Customer> querySimpleCustomerByExternalUserIds(PrivateSphere privateSphere, List<String> externalUserIds) {

        if (Objects.isNull(privateSphere) || CollectionUtils.isEmpty(externalUserIds)) {
            return new ArrayList<>();
        }

        List<List<String>> externalUserIdPartition = Lists.partition(externalUserIds, externalUserIdPartitionCount);

        List<Customer> customerList = new ArrayList<>();
        for (List<String> partition : externalUserIdPartition) {
            try {
                List<Customer> responseVo = customerServiceProxy.fetchCustomerByIds(null, partition, privateSphere);
                if (!CollectionUtils.isEmpty(responseVo)) {
                    customerList.addAll(responseVo);
                }
            } catch (Exception e) {
                log.error("查询客户信息失败,error", e);
            }
        }

        return customerList;
    }

    public SelfExternalContactGetBO queryTXCustomerInfo(PrivateSphere privateSphere, String externalUserId) {
        SelfExternalContactGetDTO selfExternalContactGetDTO = new SelfExternalContactGetDTO();
        selfExternalContactGetDTO.setCorpId(privateSphere.getCorpId());
        selfExternalContactGetDTO.setExternalUserId(externalUserId);

        if (PrivateSphereEncryptCorpEnum.CIPHER.getCode().equals(privateSphere.getEncryptCorpId())) {
            selfExternalContactGetDTO.setTemplateId(privateSphere.getTemplateId());
            selfExternalContactGetDTO.setType(WechatWorkAppType.PROXIED_INTERNAL_APP.getType());

        } else {
            selfExternalContactGetDTO.setType(WechatWorkAppType.CONTACT.getType());
        }

        selfExternalContactGetDTO.setProviderIdentity(privateSphere.getChannelProviderIdentity());

        log.info("查询外部联系人关联基本信息, request:{}", JSON.toJSONString(selfExternalContactGetDTO));
        SoaResponse<SelfExternalContactGetBO, Void> selfExternalContact = channelAdapterService.getSelfExternalContact(selfExternalContactGetDTO);
        log.info("查询外部联系人关联基本信息响应结果, request:{}, response:{}", JSON.toJSONString(selfExternalContactGetDTO), JSON.toJSONString(selfExternalContact));
        if (Objects.isNull(selfExternalContact) || Long.parseLong(selfExternalContact.getReturnCode()) != 0L) {
            log.error("查询外部联系人关联员工失败, request:{}, response:{}", JSON.toJSONString(selfExternalContactGetDTO), JSON.toJSONString(selfExternalContact));
            return null;
        }

        return selfExternalContact.getResponseVo();
    }
}
